<!DOCTYPE html>
<html xmlns:layout="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
	layout:decorate="~{common/layout}">

<head>
	<meta charset="UTF-8">
	<title>数据管理</title>
	<style>
	 
	</style>
</head>

<body>
	<div layout:fragment="fragment_body">
		<div class="toolbar">
			<div style="margin-right: 12px; width: 220px;">
				<el-input placeholder="请输入节点"></el-input>
			</div>
			<div style="flex: 1 1 0%;">
				<el-button-group>
					<el-button @click="changeStatus(null)" :type="listStatus == null ?'primary':''"
						icon="Document">全部</el-button>
					<el-button @click="changeStatus(0)" :type="listStatus == 0 ?'primary':''"
						icon="CircleCheck">已授权</el-button>
					<el-button @click="changeStatus(1)" :type="listStatus == 1 ?'primary':''"
						icon="CircleClose">未授权</el-button>
				</el-button-group>
			</div>
			<el-button v-if="list !== null && list.length > 0" 
			type="primary" @click="openForm(null)" icon="DocumentAdd">添加数据</el-button>
		</div>
		<div  v-loading="listLoading">
			<el-empty description="暂无数据" v-if="list == null || list.length == 0">
				<el-button type="primary" @click="openForm(null)" icon="DocumentAdd">开始添加一条数据吧</el-button>
			</el-empty>
			<el-table :data="list" v-if="list !== null && list.length > 0" border style="width: 100%;margin-top: 12px;">
				<el-table-column prop="dataDomaindataId" label="数据ID" width="150"></el-table-column>
				<el-table-column prop="dataTitle" label="表名" width="180"></el-table-column>
				<el-table-column prop="nodeCode" label="所属节点" width="180"></el-table-column>
				<el-table-column prop="dataRelativeName" label="文件路径" width="250">
					<template #default="scope">
						{{scope.row.dataRelativeName}}/{{scope.row.dataNativeName}}
					</template>
				</el-table-column>
				<el-table-column prop="dataType" label="类型" width="80"></el-table-column>
				<el-table-column prop="datasourceName" label="引用数据源" width="180"></el-table-column>
				<el-table-column prop="dataDomaindataId" label="状态" width="100">
					<template #default="scope">
						<el-tag size="small" type="success" v-if="scope.row.dataDomaindataId != null">已绑定</el-tag>
						<el-tag size="small" type="danger" v-if="scope.row.dataDomaindataId == null">未绑定</el-tag>
						<el-link :underline="false">
							<el-icon :size="20" color="green" @click="restatus(scope.row.dataId)">
								<Refresh></Refresh>
							</el-icon>
						</el-link>
					</template>
				</el-table-column>
				<el-table-column prop="dataDescription" label="描述"></el-table-column>
				<el-table-column prop="dataCreate" label="创建时间" width="150"></el-table-column>
				<el-table-column prop="dataId" label="操作" width="150">
					<template #default="scope">
						<el-button type="text" size="small" @click="openForm(scope.row)" >编辑</el-button>
						<el-button type="text" size="small" @click="delData(scope.row.dataId)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<!-- 详情 -->
		<el-drawer v-model="detailDrawerVisible" title="数据源详情" direction="rtl">
			<el-descriptions
			    :column="1"
			    border
			    direction="horizontal"
			    :style="blockMargin"
			    label-class-name="descriptions-label"
			  >
			    <el-descriptions-item label="所属节点">{{ossView?.nodeCode}}</el-descriptions-item>
			    <el-descriptions-item label="数据源类型">{{ossView?.datasourceType}}</el-descriptions-item>
			    <el-descriptions-item label="数据源名称">{{ossView?.datasourceName}}</el-descriptions-item>
			    
			    <el-descriptions-item label="endpoint">{{ossView?.datasourceOss.ossEndpoint}}</el-descriptions-item>
			    <el-descriptions-item label="bucket">{{ossView?.datasourceOss.ossBucket}}</el-descriptions-item>
			    <el-descriptions-item label="prefix">{{ossView?.datasourceOss.ossPrefix}}</el-descriptions-item>
			    
			    <el-descriptions-item label="accessKey">{{ossView?.datasourceOss.ossAccessKeyId}}</el-descriptions-item>
			    <el-descriptions-item label="accessSecret">{{ossView?.datasourceOss.ossAccessKeySecret}}</el-descriptions-item>
			    
			    <el-descriptions-item label="virtualhost">{{ossView?.datasourceOss.ossVirtualhost}}</el-descriptions-item>
			    <el-descriptions-item label="version">{{ossView?.datasourceOss.ossVersion}}</el-descriptions-item>
			    <el-descriptions-item label="storageType">{{ossView?.datasourceOss.ossStorageType}}</el-descriptions-item>
			    
			    <el-descriptions-item label="状态">
					<el-tag size="small" type="success" v-if="ossView.datasourceBind == 0">已绑定</el-tag>
					<el-tag size="small" type="danger" v-if="ossView.datasourceBind == 1">未绑定</el-tag>
				</el-descriptions-item>
			  </el-descriptions>
		</el-drawer>
		<!--弹框-->
		<el-dialog title="数据文件设置" v-model="dataForm.visible" width="60%">
			<el-form :model="dataForm" :rules="dataFormRules" ref="dataForm" label-width="100px">
				<el-row :gutter="10">
					<el-col :span="8">
						<h4>基础信息</h4>
						<el-form-item label="来源数据源" prop="datasourceId">
							<el-select v-model="dataForm.datasourceId" placeholder="请选择数据源" @change="dataSourceHandl">
								<el-option
							      v-for="item in dataSources"
							      :key="item.datasourceId"
							      :label="item.datasourceName"
							      :value="item.datasourceId"
							    ></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="数据节点" prop="nodeId">
							<el-select v-model="dataForm.nodeId" placeholder="请选择数据节点">
								<el-option
							      v-for="item in nodes"
							      :key="item.dnNodeId"
							      :label="item.nodeCode"
							      :value="item.dnNodeId"
							    ></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="自定义表名" prop="title">
							<el-input v-model="dataForm.title"></el-input>
						</el-form-item>
						<el-form-item label="文件路径" prop="fileDir" :disabled="dataForm.fileNameDisable">
							<el-input v-model="dataForm.fileDir">
								<template #prepend>/</template>
							</el-input>
						</el-form-item>
						<el-form-item label="上传数据" prop="remark">
							<el-upload
							    ref="uploadDataRef"
							    class="upload-demo"
							    action="data/tableStructure"
							    v-model:file-list="dataForm.dataFile"
							    :data="dataForm"
							    :auto-upload="false"
							    :limit="1"
								:before-upload="handleBeforeDataUpload"
								:on-success="handleDataSuccess"
								:on-error="handleDataError"
							  >
							    <template #trigger>
							      <el-button type="primary" text><el-icon class="el-icon--right"><Upload /></el-icon>选择数据</el-button>
							    </template>
							    <el-button class="ml-3" type="success" icon="UploadFilled" plain @click="submitDataUpload">
							      上传数据
							    </el-button>
							    <template #tip>
							      <div class="el-upload__tip">
							        请上传小于1G大小的CSV数据文件
							      </div>
							    </template>
							  </el-upload>
						</el-form-item>
						  <el-form-item label="文件地址" prop="fileName">
						  	<el-input v-model="dataForm.fileName" :disabled="dataForm.fileNameDisable">
						  		<template #prepend>/文件路径/</template>
						  	</el-input>
							<span  class="font11">如果选择文件上传则不需要填写该地址</span>
						  </el-form-item>
						  <el-form-item label="备注" prop="remark">
						  	<el-input v-model="dataForm.remark"></el-input>
						  </el-form-item>
					</el-col>
					<el-col :span="16">
						<div class="left-right">
							<h4>数据表结构</h4>
							<div >
								<el-link icon="Download" href="/demo/data.csv" target="_blank">下载数据样例</el-link>
							</div>
						</div>
						<!--<el-col>
							<div class="left-right">
								<div>
									<el-upload
									    ref="uploadStructureRef"
									    class="upload-demo"
									    action="data/tableStructure"
							    		v-model:file-list="dataForm.structureFile"
									    :auto-upload="false"
									    :limit="1"
    									:before-upload="handleBeforeStructureUpload"
    									:on-success="handleStructureSuccess"
    									:on-error="handleStructureError"
									  >
									    <template #trigger>
									      <el-button type="primary" text><el-icon class="el-icon--right"><Upload /></el-icon>选择表结构文件</el-button>
									    </template>
									    <el-button class="ml-3" type="success" plain @click="submitStructureUpload">
									      读取结构
									    </el-button>
									    <template #tip>
									      <div class="el-upload__tip">
									        请上传小于1G大小的CSV文件
									      </div>
									    </template>
									  </el-upload>
								</div>
								<div >
									<el-link icon="Download" href="/demo/data.csv" target="_blank">下载样例</el-link>
								</div>
							</div>
						</el-col>-->
						<el-col>
							<el-table :data="dataForm.structures" empty-text="请上传读取/手动添加表结构" border style="width: 100%;margin-top: 12px;">
								<el-table-column label="特征名称" width="200">
									<template #default="{ row, $index }">
										<el-form-item :prop="'structures.' + $index + '.columnName'"
										:rules="[
			                                { required: true, message: '请输入', trigger: 'blur' },
			                                { min: 1, max: 20, message: '长度在1到 20个字符', trigger: 'blur' }
			                              ]" label-width="0">
								            <el-input v-model="row.columnName"></el-input>
								         </el-form-item>
									</template>
								</el-table-column>
								<el-table-column label="类型" width="150">
									<template #default="{ row, $index}">
										<el-form-item :prop="'structures.' + $index + '.columnType'"
										:rules="[
			                                { required: true, message: '请选择', trigger: 'change' },
			                              ]" label-width="0">
								            <el-select v-model="row.columnType" placeholder="类型">
												<el-option label="int" value="int"></el-option>
												<el-option label="str" value="str"></el-option>
												<el-option label="float" value="float"></el-option>
											</el-select>
								         </el-form-item>
									</template>
								</el-table-column>
								<el-table-column label="描述（可选）">
									<template #default="{ row, $index}">
										<el-form-item :prop="'structures.' + $index + '.columnRemark'"
										:rules="[
			                                { min: 1, max: 100, message: '长度在1到100个字符', trigger: 'blur' }
			                              ]" label-width="0">
								            <el-input v-model="row.columnRemark" ></el-input>
								         </el-form-item>
									</template>
								</el-table-column>
								<el-table-column prop="columnName" label="操作" width="70">
									<template #default="scope">
										<el-button text icon="Delete" @click="onDelItem(scope.$index)"></el-button>
									</template>
								</el-table-column>
							</el-table>
						<el-button class="mt-4" style="width: 100%" @click="onAddItem()"> <el-icon><Plus /></el-icon> </el-button>
						</el-col>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<el-button @click="closeForm">取 消</el-button>
				<el-button type="primary" @click="saveForm">保 存</el-button>
			</template>
		</el-dialog>
	</div>
</body>
<script type="text/javascript" layout:fragment="fragment_script">
	const _data = {
		list: [],
		dataSources: [],
		nodes: [],
		detailDrawerVisible: false,
		listStatus: null,
		listLoading: false,
		dataForm: {
			visible: false,
			id: '',
			datasourceId: '',
			nodeId: '',
			title: '',
			fileDir: '',
			fileName: '',
			fileNameDisable: false,
			remark: '',
			structures: [],
			dataFile: [],
			structureFile: [],
		},
		dataFormRules: {
			datasourceId: [
				{required: true, message: '请选择数据源', trigger: 'change'}
			],
			nodeId: [
				{required: true, message: '请选择节点', trigger: 'change'}
			],
			title: [
				{required: true, message: '不能为空', trigger: 'blur'}
			],
			fileDir: [
				{required: false, message: '不能为空', trigger: 'blur'}
			],
			fileName: [
				{required: true, message: '不能为空', trigger: 'blur'}
			],
			structures: [
				{required: true, message: '请设置表结构', trigger: 'blur'}
			]
		},
		ossView: null
	}
	const _method = {
		loadDsList() {
			let that = this
			getRequst('/dataSource/list').then(function (resp) {
				that.dataSources = resp.data
			})
		},
		dataSourceHandl(){
			that.dataForm.nodeId = null
			that.loadNodeList()
		},
		loadNodeList() {
			let that = this
			getRequst('/dataSource/nodes?dsId=' + that.dataForm.datasourceId).then(function (resp) {
				that.nodes = resp.data
			})
		},
		openDetail(row) {
			this.ossView =  row
			this.detailDrawerVisible = true
		},
		changeStatus(val) {
			this.listStatus = val
		},
		openForm(row) {
			if(row){
				that.dataForm = {
					id: row.dataId,
					datasourceId: row.dataSourceId,
					nodeId: row.dataNodeId,
					title: row.dataTitle,
					fileDir: row.dataRelativeName,
					fileName: row.dataNativeName,
					fileNameDisable: false,
					remark: row.dataDescription,
					structures: row.columnList,
					dataFile: [],
					structureFile: [],
					visible: true
				}
			}else{
				that.dataForm = {
					id: '',
					datasourceId: '',
					nodeId: '',
					title: '',
					fileDir: '',
					fileName: '',
					fileNameDisable: false,
					remark: '',
					structures: [],
					dataFile: [],
					structureFile: [],
					visible: true
				}
			}
		},
		delData(dataId){
			getRequst('/data/remove?dataId=' + dataId).then(function (resp) {
				if (resp.status == 0) {
					that.loadList()
					that.$message({message: resp.msg, type: "success"});
				} else {
					that.$message({message: resp.msg, type: "error"});
				}
			})
		},
		closeForm() {
			this.$refs["dataForm"].resetFields();
			this.dataForm.visible = false
		},
		saveForm() {
			let that = this
			that.$refs["dataForm"].validate((valid) => {
				if (valid) {
					if(!that.dataForm.structures || that.dataForm.structures.length == 0){
						that.$message.error("请编辑表结构");
						return false
					}
					let loading = that.$loading()
					postRequst('/data/create', that.dataForm).then(function (resp) {
						loading.close()
						if (resp.status == 0) {
							that.loadList()
							that.dataForm.visible = false
							that.$refs["dataForm"].resetFields();
							that.$message({message: resp.msg, type: "success"});
						} else {
							that.$message({message: resp.msg, type: "error"});
						}
					})
				}
			});
		},
		loadList() {
			let that = this
			that.listLoading = true
			getRequst('/data/list').then(function (resp) {
				that.list = resp.data
				that.listLoading = false
			})
		},
		/**loadStructureList() {
			let that = this
			getRequst('/data/tableStructure').then(function (resp) {
				that.dataForm.structures = resp.data
			})
		},**/
		restatus(dataId) {
			let that = this
			let loading = that.$loading()
			getRequst('/data/restatus?dataId=' + dataId).then(function (resp) {
				loading.close()
				if (resp.status == 0) {
					that.loadList()
					that.$message({message: resp.msg, type: "success"});
				} else {
					that.$message({message: resp.msg, type: "error"});
				}
			})
		},
		/**handleBeforeStructureUpload(file){
			let that = this
			var suffix = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
			let isSuffix = (suffix === 'csv')
			if (!isSuffix) {
				that.$message.error("只能上传csv文件");
				return false
			}
			let isLt1M = file.size / 1024 / 1024 < 1000;
			if (!isLt1M) {
				that.$message.error('文件大小不能超过 1GB');
				return false
			}
			return true;
		},**/
		/**handleStructureSuccess(response, file, fileList) {
	      this.dataForm.structures = []
		  if(response.data.status == 0){
	      	that.dataForm.structures = response.data
	      	that.$message({message: response.data.msg, type: "success"});
		  }else{
			that.$message.error(response.data.msg);
	      	this.dataForm.structures = null
		  }
	      that.$refs.uploadStructureRef.clearFiles()
	    },**/
	    /**handleStructureError(err, file, fileList) {
	      this.dataForm.structures = []
	      that.$refs.uploadStructureRef.clearFiles()
	    },**/
		/**submitStructureUpload(){
			let that = this
			if(!that.dataForm.structureFile){
				that.$message.error("未选择表结构文件");
				return false
			}
      		that.$nextTick(() => {
				  that.$refs.uploadStructureRef.submit()
			  })
		},**/
		handleBeforeDataUpload(file){
			let that = this
			var suffix = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
			let isSuffix = (suffix === 'csv')
			if (!isSuffix) {
				that.$message.error("只能上传csv文件");
				return false
			}
			let isLt1M = file.size / 1024 / 1024 < 1000;
			if (!isLt1M) {
				that.$message.error('文件大小不能超过 1GB');
				return false
			}
			return true;
		},
		handleDataSuccess(response, file, fileList) {
		  if(response.status == 0){
			that.dataForm.fileName = response.data.uploadRes.data.rename
			that.dataForm.fileNameDisable = true,
			that.dataForm.structures = response.data.structures
			//that.dataForm.fileDir = response.data.path
	      	that.$message({message: response.msg, type: "success"});
		  }else{
			  that.$message.error(response.msg);
			  this.dataForm.fileName = null
			  this.dataForm.fileDir = null
		  }
	      that.$refs.uploadDataRef.clearFiles()
	    },
	    handleDataError(err, file, fileList) {
		  this.dataForm.fileName = null
	      this.dataForm.fileDir = null
	      that.$refs.uploadDataRef.clearFiles()
	    },
		submitDataUpload(){
			let that = this
			let dsV = false
			//let fileNameV = false
			let fileDirV = false
			that.$refs["dataForm"].validateField('datasourceId', (valid) => {
	          dsV = valid
        	});
			//that.$refs["dataForm"].validateField('fileName', (valid) => {
	          //fileNameV = valid
        	//});
			that.$refs["dataForm"].validateField('fileDir', (valid) => {
	          fileDirV = valid
        	});
			setTimeout(function(){
				if(dsV && fileDirV){
					if(!that.dataForm.dataFile){
						that.$message.error("未选择数据文件");
						return false
					}
					that.$nextTick(() => {
					  that.$refs.uploadDataRef.submit()
				  	})
				}
			}, 100)
		},
	    onDelItem(index){
			this.dataForm.structures.splice(index, 1)
		},
	    onAddItem() {
			if(!this.dataForm.structures){
				this.dataForm.structures = []
			}
			this.dataForm.structures.push({
				columnName: '',
				columnType: '',
				columnRemark: ''
			})
		},
	}
	function _created() {
		this.loadDsList()
		this.loadList()
	}
	//const _watch = {}
</script>

</html>